package com.maycurobj.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.request.OapiSmartworkHrmEmployeeV2UpdateRequest.*;
import com.dingtalk.api.response.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.maycur.developer.sdk.common.exception.MaycurException;
import com.maycur.developer.sdk.maycur.ultimate.openapi.request.DeleteEmployeeBatchRequest;
import com.maycurobj.configuration.ConfInfo;
import com.maycurobj.entity.bim.IamLeaveUser;
import com.maycurobj.pojo.DingEmployeeInfo;
import com.maycurobj.repository.bim.IamLeaveUserRepository;
import com.maycurobj.service.http.HttpAPIService;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 钉钉api
 * 相关服务
 */
@Service
@Slf4j
public class DingTalkService {

    @Autowired
    private ConfInfo confInfo;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private IamLeaveUserRepository iamLeaveUserRepository;


    @Autowired
    private HttpAPIService httpAPIService;

    @Value("${dingmsg.urlpath}")
    private String DINGMSGURL;

    /**
     * 推送钉钉信息到手机号
     */
    public void pushDingMsg(String msg,String[] phone){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phones", phone);
        jsonObject.put("msg", msg);
        String url = DINGMSGURL;
        try{
            httpAPIService.doPost(url, JSONObject.toJSONString(jsonObject));
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    //获取token
    public String getAccenToken() {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(confInfo.getDingAppKey());
        request.setAppsecret(confInfo.getDingAppSecret());
        request.setHttpMethod("GET");
        try {
            OapiGettokenResponse response = client.execute(request);
            System.out.println("请求token接口返回：" + response.getBody());
            JSONObject jsonObject = objectMapper.readValue(response.getBody(), JSONObject.class);
            if (jsonObject.getIntValue("errcode") == 0) {
                System.out.println("token:" + jsonObject.getString("access_token"));
                return jsonObject.getString("access_token");
            } else {
                return null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();

        }
        return null;
    }

    //根据userid获取用户详情
    public String getDingUser(String userid) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
        OapiV2UserGetRequest req = new OapiV2UserGetRequest();
        req.setUserid(userid);
        req.setLanguage("zh_CN");
        try{
            OapiV2UserGetResponse response=client.execute(req,getAccenToken());
            System.out.println(objectMapper.writeValueAsString(response.getBody()));
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 更新花名册信息
     * 传入需要更新的用户信息
     */
    public void updateHrmEmployeeInfo(DingEmployeeInfo dingEmployeeInfo,Long agentId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/v2/update");
        OapiSmartworkHrmEmployeeV2UpdateRequest request = new OapiSmartworkHrmEmployeeV2UpdateRequest();
        request.setAgentid(agentId);
        EmpUpdateByCustomParam param = new EmpUpdateByCustomParam();
        List<EmpGroupFieldVo> groups = new ArrayList<>();
        groups.add(getGroup("sys04-bankAccountNo", dingEmployeeInfo.getBankAccountNo(), "sys04", 0L));
        groups.add(getGroup("sys04-accountBank", dingEmployeeInfo.getAccountBank(), "sys04", 0L));
        groups.add(getGroup("sys00-workPlace", dingEmployeeInfo.getWorkPlace(), "sys00", 0L));
        groups.add(getGroup("sys00-reportManager", dingEmployeeInfo.getReportManager(), "sys00", 0L));

        param.setUserid(dingEmployeeInfo.getUserId());
        param.setGroups(groups);
        request.setParam(param);

        try{
            System.out.println("请求json:"+objectMapper.writeValueAsString(request));
            OapiSmartworkHrmEmployeeV2UpdateResponse rsp = client.execute(request, getAccenToken());
            log.info("更新花名册结果:{}", objectMapper.writeValueAsString(rsp.getBody()));
        }catch(Exception ex){
            ex.printStackTrace();

        }
    }

    /**
     * 获取近2天员工离职信息，更新钉钉部门信息
     */
    public void handleEmployeeLeave() {
        List<IamLeaveUser> rets = iamLeaveUserRepository.getLists(2);
        for (IamLeaveUser user : rets) {
            try {
                getUserIdAndUpdateDepartment(user.getMobile());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据离职人员手机号 更新部门
     * @param mobile
     * @return
     */
    public String getUserIdAndUpdateDepartment(String mobile) {
        try {
            // 根据手机号获取用户ID
            DingTalkClient clientGet = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest reqGet = new OapiV2UserGetbymobileRequest();
            reqGet.setMobile(mobile);
            reqGet.setSupportExclusiveAccountSearch(true);
            OapiV2UserGetbymobileResponse rspGet = clientGet.execute(reqGet, getAccenToken());

            JSONObject json = JSON.parseObject(rspGet.getBody());
            if (json.getIntValue("errcode") == 0) {
                JSONObject result = json.getJSONObject("result");
                JSONArray list = result.getJSONArray("exclusive_account_userid_list");
                if (list != null && !list.isEmpty()) {
                    String userId = list.getString(0);
                    //更新用户的部门
                    DingTalkClient clientUpdate = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/update");
                    OapiV2UserUpdateRequest reqUpdate = new OapiV2UserUpdateRequest();
                    reqUpdate.setUserid(userId);
                    reqUpdate.setDeptIdList("981710023");
                    OapiV2UserUpdateResponse rspUpdate = clientUpdate.execute(reqUpdate, getAccenToken());
                    System.out.println(rspUpdate.getBody());
                    // 成功则返回 userId
                    if (rspUpdate.getErrcode() == 0) {
                        return userId;
                    } else {
                        System.err.println("更新部门失败: " + rspUpdate.getErrmsg());
                    }
                }
            } else {
                System.err.println("获取用户失败: " + json.getString("errmsg"));
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    //获取钉钉花名册
    public void getDingTalkEmployeeList() {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
            OapiV2UserListRequest req = new OapiV2UserListRequest();
            req.setCursor(0l);
            req.setContainAccessLimit(true);
            req.setDeptId(154295893l);
            req.setSize(100l);
            OapiV2UserListResponse rsp = client.execute(req, getAccenToken());
            System.out.println("打印返回"+JSONObject.toJSONString(rsp));
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 不知道干啥的
     * @param fieldCode
     * @param value
     * @param groupId
     * @param index
     * @return
     */
    private EmpGroupFieldVo getGroup(String fieldCode,String value,String groupId,Long index){
        EmpGroupFieldVo group = new EmpGroupFieldVo();
        List<EmpListFieldVo> sections = new ArrayList<>();
        EmpListFieldVo section = new EmpListFieldVo();
        List<EmpFieldVo> fieldVos = new ArrayList<>();
        EmpFieldVo fieldVo = new EmpFieldVo();
        fieldVo.setFieldCode(fieldCode);
        fieldVo.setValue(value);
        fieldVos.add(fieldVo);
        section.setOldIndex(index);
        section.setSection(fieldVos);
        sections.add(section);
        group.setGroupId(groupId);
        group.setSections(sections);

        return group;
    }
}
